package HTTP

import (
	"SQL/FSDB"
	"encoding/json"
	"net/http"
)

func addGroup(w http.ResponseWriter, req *http.Request) {

	var resCode = Success
	var msg = ""
	var res interface{}
	defer func() {
		writeResult(w, resCode, msg, res)
	}()

	nickname := req.FormValue("nickname")
	icon := req.FormValue("icon")
	customInfo := req.FormValue("customInfo")

	ok := false
	if ok, resCode, msg = isArgsEmpty(nickname, icon, customInfo); ok {
		return
	}
	if ok, resCode, msg = isValidNickname(nickname); !ok {
		return
	}
	if ok, resCode, msg = isValidIcon(icon); !ok {
		return
	}
	if ok, resCode, msg = isValidCustomInfo(customInfo); !ok {
		return
	}

	customJSON, err := json.Marshal(customInfo)
	if err != nil {
		msg = "customInfo解析失败！\n错误详情：" + err.Error()
		resCode = errMarshalJSONFailed
		return
	}
	errCode, errMsg, newGroupID := writeGroupToDB(nickname, icon, customJSON)
	msg = errMsg
	if errCode != Success {
		resCode = errCode
		return
	}
	res = newGroupID
}

func writeGroupToDB(nickname string, icon string, customInfo []byte) (errCode int, errMsg string, newGroupID int) {

	addGroupSQL := `INSERT INTO 
						objects(nickname,icon,isuser,custom) 
					VALUES($1,$2,false,$3);`
	tx, err := FSDB.BeginTx()
	defer func() {
		if errCode != Success {
			err := tx.Rollback()
			if err != nil {
				errCode = errEndTx
				errMsg = err.Error()
			}
		}
	}()
	if err != nil {
		errCode = errDBExecFailed
		errMsg = err.Error()
		return
	}
	_, err = FSDB.ExecTx(tx, addGroupSQL, nickname, icon, customInfo)
	if err != nil {
		errCode = errDBExecFailed
		errMsg = err.Error()
		return
	}
	lastInsertIDSQL := `SELECT currval(pg_get_serial_sequence('objects', 'id'));`
	rows, err := tx.Query(lastInsertIDSQL)
	defer rows.Close()
	if err != nil {
		errCode = errDBExecFailed
		errMsg = err.Error()
		return
	}
	var currval = -1
	for rows.Next() {
		err := rows.Scan(&currval)
		if err != nil {
			errCode = errDBExecFailed
			errMsg = err.Error()
			return
		}
	}
	if currval == -1 {
		errCode = errDBExecFailed
		errMsg = "创建群失败"
		return
	}

	date := currentTime()
	insertGroupSQL := `INSERT INTO groups(id,createTime) 
						VALUES($1,$2);`
	_, err = FSDB.ExecTx(tx, insertGroupSQL, currval, date)
	if err != nil {
		errCode = errDBExecFailed
		errMsg = "创建群失败"
		return
	}
	tx.Commit()
	return Success, "创建群成功！", currval
}
